package com.ruoyi.shenji.listenner;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.shenji.domain.TableData;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class TableDataListener implements ReadListener<TableData> {
    // 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
    private static final int BATCH_COUNT = 100;
    private List<TableData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<TableData> demoDatatEntityList = new ArrayList();
    private String fileName;



    /**
     * 在监听器出现异常时会调用此方法
     */
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception.getClass() == ExcelAnalysisStopException.class) {
            System.out.println("解析失败" + exception.getMessage());
            throw exception;
        } else {
            System.out.println("解析失败，但是继续解析下一行:" + exception.getMessage());
            if (exception instanceof ExcelDataConvertException) {
                ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
                System.out.println("第" + excelDataConvertException.getRowIndex() + "行，第" + excelDataConvertException.getColumnIndex() + "列解析异常，数据为:" + excelDataConvertException.getCellData());
            }

        }
    }

    @Override
    public void invoke(TableData tableData, AnalysisContext analysisContext) {
        this.cachedDataList.add(tableData);
        if (this.cachedDataList.size() >= BATCH_COUNT) {
            this.transData();
            this.cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 每一条头数据解析都会来调用
     */
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        System.out.println("解析到一条头数据:" + JSON.toJSONString(headMap));
        if (headMap.size() < 1) {
            throw new ExcelAnalysisStopException("读取excel模板不匹配");
        }
    }

    /**
     * 这个每一条数据解析都会来调用
     */


    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        this.transData();
    }

    private void transData() {
        // ...数据转换的内容
    }
}